<?php
class Customers_Admin extends MX_Controller
{
    private $_last_message = '';
    function __construct()
    {
        parent::__construct();
        if(!modules::run('auth/auth/has_permission', array('operation' => OPERATION_MANAGE))) redirect('/');
//        $this->output->enable_profiler(TRUE);
    }

    /**
     * Sắp xếp layout, chuẩn bị dữ liệu cho module customers
     *
     * @param type $method
     * @param type $para1
     * @param type $para2
     */
    function dispatcher($method='dashboard', $para1=NULL, $para2=NULL)
    {
        $layout             = 'powercms/admin_layout';
        $current_url        = '';

        switch ($method)
        {
            case 'list_customer':
                $main_content           = $this->list_customers(array('page' => $para1));
                $current_url            = '/dashboard/customers';
                break;
            case 'add_customer':
                $main_content           = $this->add_customer();
                break;
            case 'edit_customer':
                $main_content           = $this->edit_customer(array('customer_id' => $para1));
                break;
            case 'detail_customer':
                $main_content           = $this->detail_customer(array('customer_id' => $para1, 'page' => $para2));
                break;
            case 'delete_customer':
                $main_content           = $this->delete_customer(array('customer_id' => $para1));
                break;
            case 'add_customer_file':
                $this->output->link_js('/powercms/scripts/jquery/ui.datepicker.js');
                $this->output->javascripts('setup_datepicker()');
                $main_content           = $this->add_customer_file(array('customer_id' => $para1));
                break;
            case 'edit_customer_file':
                $this->output->link_js('/powercms/scripts/jquery/ui.datepicker.js');
                $this->output->javascripts('setup_datepicker()');
                $main_content           = $this->edit_customer_file(array('customer_id' => $para1, 'file_id' => $para2));
                break;
        }

        $view_data                  = array();
        $view_data['url']           = isset($current_url) ? $current_url : '';
        $view_data['admin_menu']    = modules::run('menus/menus/get_dashboard_menus');
        $view_data['main_content']  = $main_content;
        // META data
        $view_data['title']         = $this->_title;
        $this->load->view($layout, $view_data);
    }

    function list_customers($options = array())
    {
        $options                = array_merge($options, $this->_prepare_search($options));
        $options['is_admin']    = TRUE;
        $total_row              = $this->customers_model->get_customers_count($options);
        $total_pages            = (int)($total_row / CUSTOMERS_PER_PAGE);
        if ($total_pages * CUSTOMERS_PER_PAGE < $total_row) $total_pages++;
        if ((int)$options['page'] > $total_pages) $options['page'] = $total_pages;

        $options['offset']  = $options['page'] <= DEFAULT_PAGE ? DEFAULT_OFFSET : ((int)$options['page'] - 1) * CUSTOMERS_PER_PAGE;
        $options['limit']   = CUSTOMERS_PER_PAGE;
//        $options['role_id'] = ID_MANAGER;
        $config = prepare_pagination(
            array(
                'total_rows'    => $total_row,
                'per_page'      => $options['limit'],
                'offset'        => $options['offset'],
                'js_function'   => 'change_page_admin'
            )
        );
        $this->pagination->initialize($config);

        $view_data  = array();
        //$countries
        $view_data['page_links']    = $this->pagination->create_ajax_links();
        $view_data['customers']         = $this->customers_model->get_customers($options);
        $view_data['total_rows']    = $total_row;
        $view_data['total_pages']   = $total_pages;
        $view_data['page']          = $options['page'];
        $view_data['filter']        = $options['filter'];
        //heading
        $this->_title       = 'Quản lý khách hàng' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/customers_list', $view_data, TRUE);
    }


    /*
     * Thêm mới customer
     */
    function add_customer()
    {
        $options    = array();
        if($this->is_postback())
        {
            if (!$this->_do_add_customer())
                $options['error'] = $this->_last_message;
        }
        $view_data = $this->_get_add_customer_form_data();
        
        if (isset($options['error'])) $view_data['options']   = $options;

        $this->_title               = 'Thêm mới khách hàng' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_customer_form', $view_data, TRUE);
    }
 /**
     * Chuẩn bị dữ liệu cho form add
     * @return type
     */
    private function _get_add_customer_form_data()
    {
        $view_data                  = array();
        $view_data['name']          = $this->input->post('name');
        $view_data['password']      = $this->input->post('password');
        $view_data['code']          = $this->input->post('code');
        $view_data['phone']         = $this->input->post('phone');
        $view_data['address']       = $this->input->post('address');
        $view_data['email']         = $this->input->post('email');
        $view_data['header']        = 'Thêm khách hàng';
        $view_data['button_name']   = 'Thêm';
        $view_data['submit_uri']    = '/dashboard/customers/add';
        return $view_data;
    }
    
    private function _do_add_customer()
    {
        $this->form_validation->set_rules('name', 'Tên khách hàng', 'trim|required|xss_clean');
        $this->form_validation->set_rules('code', 'Mã số', 'trim|required|xss_clean');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean|');
        $this->form_validation->set_rules('phone', 'Số điện thoại', 'trim|required|xss_clean|is_numberic');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'trim|required|xss_clean');
        
        if ($this->form_validation->run())
        {
            $post_data = $this->_get_posted_customer_data();

            $customers = $this->customers_model->get_customers(array('code'=> $post_data['code'],'last_row' => TRUE));
            if(is_object($customers))
            {
                $this->_last_message = 'Mã số này đã tồn tại trong hệ thống';
                return FALSE;
            }
            else
            {
                $this->customers_model->add_customer($post_data);
                redirect('/dashboard/customers/' . $this->phpsession->get('current_support_lang'));
            }
        }
        $this->_last_message = validation_errors();
        return FALSE;
    }

    private function _get_posted_customer_data(){
        $view_data                   = array();
        $view_data['name']           = $this->input->post('name');
        $view_data['code']           = $this->input->post('code');
        $view_data['password']       = md5($this->input->post('password'));
        $view_data['address']        = $this->input->post('address');
        $view_data['phone1']         = $this->input->post('phone');
        $view_data['email']          = $this->input->post('email');
        $view_data['created_date']   = date('Y-m-d H:i:s');
        return $view_data;
    }


    /**
     * Thực hiện việc sửa nội dung sản phẩm.
     *
     */
    function edit_customer($options = array())
    {
        // Nếu là postback thì lưu dữ liệu và quay trở lại trang danh sách
        if ($this->is_postback())
        {
            if (!$this->_do_edit_customer($options))
                $options['error'] = $this->_last_message;
        }
        // Hiển thị form sửa sản phẩm
        $view_data                  = $this->_get_edit_customer_form_data($options);
        if (isset($options['error'])) $view_data['options'] = $options;
        $view_data['submit_uri']   = '/dashboard/customers/edit/'.$options['customer_id'];
        $view_data['header']        = 'Sửa thông tin khách hàng';
        $view_data['button_name']   = 'Lưu lại';
        $view_data['is_edit']       = TRUE;
        //heading
        $this->_title               = 'Sửa thông tin khách hàng' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_customer_form', $view_data, TRUE);
    }

    /**
     * Lấy dữ liệu cho form đăng sản phẩm mới
     */
    private function _get_edit_customer_form_data($options = array())
    {
        $customer_id                     = $options['customer_id'];
        $view_data                   = array();

        // Get from DB
        if(!$this->is_postback())
        {
            $customers                       = $this->customers_model->get_customers(array('id' => $customer_id, 'is_admin' => TRUE, 'last_row'=> 'ok'));
            if(!is_object($customers)) show_404();
            $view_data['name']          = $customers->name;
            $view_data['code']            = $customers->code;
            $view_data['password']      = '';
            $view_data['email']         = $customers->email;
            $view_data['address']       = $customers->address;
            $view_data['phone']         = $customers->phone1;
        }
//        // Get from submit
        else
        {
            $view_data                  = array();
            $view_data['name']          = $this->input->post('name');
            $view_data['code']          = $this->input->post('code');
            $view_data['password']      = $this->input->post('password');
            $view_data['phone']         = $this->input->post('phone');
            $view_data['address']       = $this->input->post('address');
            $view_data['email']         = $this->input->post('email');
        }
        return $view_data;
    }

    /**
     * Thực hiện việc thêm sản phẩm vào trong DB
     * @return type
     */
    private function _do_edit_customer($options = array())
    {
        $this->form_validation->set_rules('name', 'Tên khách hàng', 'trim|required|xss_clean');
        $this->form_validation->set_rules('code', 'Mã số', 'trim|required|xss_clean|');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean|');
        $this->form_validation->set_rules('phone', 'Số điện thoại', 'trim|required|xss_clean|is_numberic');
        $this->form_validation->set_rules('address', 'Địa chỉ', 'trim|required|xss_clean');
        if ($this->form_validation->run($this))
        {

            $view_data                          = array();
            if($this->input->post('password') != '')
                $view_data['password']   = md5($this->input->post('password'));
            $view_data['name']          = $this->input->post('name');
            $view_data['phone1']         = $this->input->post('phone');
            $view_data['address']        = $this->input->post('address');
            $view_data['email']          = $this->input->post('email');
            $view_data['id']            = $options['customer_id'];
            $this->customers_model->update_customer($view_data);
            redirect('/dashboard/customers');
        }
        $this->_last_message = validation_errors();
        return FALSE;
    }

    function delete_customer($options = array())
    {
        $customer_id = $options['customer_id'];
        
        $arr = $this->customers_model->get_customers(array('id' => $customer_id, 'last_row'=>'last_row'));
        
        if(!is_object($arr)){
             show_404('');
        }
        // xóa ảnh
        $this->customers_model->delete_customer($customer_id);
        redirect('/dashboard/customers');
    }


    function process_status()
    {
        $id = $this->input->post('id');
        $customer = $this->customers_model->get_customers(array('id' =>$id, 'is_admin' => TRUE));
        $status = $customer->status == ACTIVE_PRODUCT ? INACTIVE_PRODUCT : ACTIVE_PRODUCT;
        $this->customers_model->change_status($id, $status);
    }


    private function _prepare_search($options = array())
    {
        $search_condition = array();
        // nếu submit
        if($this->is_postback())
        {
            $search_condition['name']           = $this->db->escape_str($this->input->post('name'));
            $search_condition['code']           = $this->input->post('code');
            $search_condition['address']        = $this->input->post('address');
            $search_condition['phone']          = $this->input->post('phone');
            $search_condition['email']          = $this->input->post('email');
            $this->phpsession->save('customers_search', $search_condition);
            $customers_search                    = $this->phpsession->get('customers_search');
        }
        else
        {
            $customers_search                = $this->phpsession->get('customers_search');
        }
        
        $options['name']        = isset($customers_search['name']) ? $customers_search['name'] : '';
        $options['code']        = isset($customers_search['code']) ? $customers_search['code'] : '';
        $options['address']     = isset($customers_search['address']) ?  $customers_search['address'] : '';
        $options['phone']       = isset($customers_search['phone']) ? $customers_search['phone'] : '';
        $options['email']       = isset($customers_search['email']) ? $customers_search['email'] : '';
        $options['filter']      = $this->load->view('admin/filter_form', $options, TRUE);
        return $options;
    }
    
    function detail_customer($options = array())
    {
        $options['is_admin']    = TRUE;
        $total_row              = $this->customers_model->get_customers_files_count($options);
        $total_pages            = (int)($total_row / CUSTOMERS_PER_PAGE);
        if ($total_pages * CUSTOMERS_PER_PAGE < $total_row) $total_pages++;
        if ((int)$options['page'] > $total_pages) $options['page'] = $total_pages;

        $options['offset']  = $options['page'] <= DEFAULT_PAGE ? DEFAULT_OFFSET : ((int)$options['page'] - 1) * CUSTOMERS_PER_PAGE;
        $options['limit']   = CUSTOMERS_PER_PAGE;
        $config = prepare_pagination(
            array(
                'total_rows'    => $total_row,
                'per_page'      => $options['limit'],
                'offset'        => $options['offset'],
                'js_function'   => 'change_page_admin'
            )
        );
        $this->pagination->initialize($config);

        $view_data  = array();
        $view_data['page_links']    = $this->pagination->create_ajax_links();
        $view_data['files']     = $this->customers_model->get_customer_files($options);
        $view_data['total_rows']    = $total_row;
        $view_data['total_pages']   = $total_pages;
        $view_data['page']          = $options['page'];
        $view_data['customers_array']= $this->customers_model->get_customers_array();
        $view_data['customer_id']   = $options['customer_id'];
        //heading
        $this->_title       = 'Hồ sơ các lần khám của khách hàng' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/customers_files', $view_data, TRUE);
    }
    
     /*
     * Thêm mới customer
     */
    function add_customer_file($options = array())
    {
        if($this->is_postback())
        {
            if (!$this->_do_add_customer_file($options))
                $options['error'] = $this->_last_message;
        }
        $view_data = $this->_get_add_customer_file_form_data($options);
        
        if (isset($options['error'])) $view_data['options']   = $options;

        $this->_title               = 'Thêm mới hồ sơ' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_customer_file_form', $view_data, TRUE);
    }
 /**
     * Chuẩn bị dữ liệu cho form add
     * @return type
     */
    private function _get_add_customer_file_form_data($options = array())
    {
        $view_data                  = array();
        $view_data['title']         = $this->input->post('title');
        $view_data['content']       = '';
        if($this->is_postback())
            $view_data['registered_date']  = $this->input->post('registered_date');
        else
            $view_data['registered_date']  = date('d/m/Y');
        $view_data['header']        = 'Thêm hồ sơ';
        $view_data['button_name']   = 'Thêm';
        $view_data['submit_uri']    = '/dashboard/customers/detail/'.$options['customer_id'].'/add';
        $view_data['customer_id']   = $options['customer_id'];
        $view_data['scripts']       = $this->_get_scripts();
        return $view_data;
    }
    
    private function _do_add_customer_file($options = array())
    {
        $this->form_validation->set_rules('title', 'Tiêu đề', 'trim|required|xss_clean');
        $this->form_validation->set_rules('content', 'Nội dung', 'trim|required|xss_clean');
        $this->form_validation->set_rules('registered_date', 'Ngày khám', 'trim|required|xss_clean|');
        
        if ($this->form_validation->run())
        {
            $post_data = $this->_get_posted_customer_file_data($options);
            $this->customers_model->add_customer_file($post_data);
            redirect('/dashboard/customers/detail/' . $options['customer_id']);
        }
        $this->_last_message = validation_errors();
        return FALSE;
    }

    private function _get_posted_customer_file_data($options = array())
    {
        $view_data                   = array();
        $view_data['title']          = $this->input->post('title');
        $view_data['content']        = $this->input->post('content');
        $view_data['registered_date']= convert_date_to_format_sql($this->input->post('registered_date'));
        $view_data['created_date']   = date('Y-m-d H:i:s');
        $view_data['thumbnail']      = $this->upload_thumbnails();
        $view_data['customer_id']    = $options['customer_id'];
        return $view_data;
    }
    
    function edit_customer_file($options = array())
    {
        // Nếu là postback thì lưu dữ liệu và quay trở lại trang danh sách
        if ($this->is_postback())
        {
            if (!$this->_do_edit_customer_file($options))
                $options['error'] = $this->_last_message;
        }
        // Hiển thị form sửa sản phẩm
        $view_data                  = $this->_get_edit_customer_file_form_data($options);
        if (isset($options['error'])) $view_data['options'] = $options;
        $view_data['submit_uri']   = '/dashboard/customers//detail/' . $options['customer_id'] . '/edit/'.$options['file_id'];
        $view_data['header']        = 'Sửa thông tin hồ sơ';
        $view_data['button_name']   = 'Lưu lại';
        $view_data['customer_id']   = $options['customer_id'];
        $view_data['scripts']       = $this->_get_scripts();
        //heading
        $this->_title               = 'Sửa thông tin hồ sơ' . DEFAULT_TITLE_SUFFIX;
        return $this->load->view('admin/add_customer_file_form', $view_data, TRUE);
    }

    /**
     * Lấy dữ liệu cho form đăng sản phẩm mới
     */
    private function _get_edit_customer_file_form_data($options = array())
    {
        $file_id                     = $options['file_id'];
        $view_data                   = array();

        // Get from DB
        if(!$this->is_postback())
        {
            $customers_file                       = $this->customers_model->get_customer_files(array('id' => $file_id, 'is_admin' => TRUE));
            if(!is_object($customers_file)) show_404();
            $view_data['title']         = $customers_file->title;
            $view_data['content']       = $customers_file->content;
            $view_data['registered_date']= date('d/m/Y', strtotime($customers_file->registered_date));
            $view_data['thumbnail']      = $customers_file->thumbnail;
        }
//        // Get from submit
        else
        {
            $view_data                  = array();
            $view_data['title']         = $this->input->post('title');
            $view_data['content']       = $this->input->post('content');
            $view_data['registered_date']= $this->input->post('registered_date');
            $view_data['thumnail']      = $this->input->post('thumbnail');
        }
        return $view_data;
    }

    /**
     * Thực hiện việc thêm sản phẩm vào trong DB
     * @return type
     */
    private function _do_edit_customer_file($options = array())
    {
        $this->form_validation->set_rules('title', 'Tiêu đề', 'trim|required|xss_clean');
        $this->form_validation->set_rules('content', 'Nội dung', 'trim|required|xss_clean');
        $this->form_validation->set_rules('registered_date', 'Ngày khám', 'trim|required|xss_clean|');
        if ($this->form_validation->run($this))
        {

            $view_data                      = array();
            $view_data['title']             = $this->input->post('title');
            $view_data['content']           = $this->input->post('content');
            $view_data['registered_date']   = convert_date_to_format_sql($this->input->post('registered_date'));
            $view_data['id']                = $options['file_id'];
            $thumbnail  = $this->upload_thumbnails();
            if($thumbnail != NULL)
            {
                $view_data['thumbnail']             = $thumbnail;
                $file = $this->customers_model->get_customer_files(array('id' => $options['file_id']));
                if($file->thumbnail != '' && $file->thumbnail != NULL)
                    if (file_exists('./images/files/' . $file->thumbnail))
                        unlink('./images/files/' . $file->thumbnail);
                
            }
            $this->customers_model->update_customer_file($view_data);
            redirect('/dashboard/customers/detail/' . $options['customer_id']);
        }
        $this->_last_message = validation_errors();
        return FALSE;
    }
    
    function delete_customer_file($customer_id = 0, $file_id = 0)
    {
        $this->customers_model->delete_customer_file($file_id);
        redirect('/dashboard/customers/detail/' . $customer_id);
    }
    
    
    function upload_thumbnails()
    {
        $config = array();
        $config['upload_path'] = './images/files/';
        $config['allowed_types'] = 'png|jpg|jpeg|gif';
        $config['max_size']	= '1024';
//        $config['width'] = 800;
//        $config['height'] = 600;
        $this->load->library('upload', $config);
        if ( ! $this->upload->do_upload())
        {
//                return $this->upload->display_errors();
            return NULL;
        }
        else
        {
                $data = $this->upload->data();
                return $data['file_name'];
        }
    }
        private function _get_scripts()
    {
        $scripts                     = '<script type="text/javascript" src="/powercms/scripts/tiny_mce/tiny_mce.js?v=20111006"></script>';
        $scripts                    .= '<script language="javascript" type="text/javascript" src="/powercms/scripts/tiny_mce/plugins/imagemanager/js/mcimagemanager.js?v=20111006"></script>';
        $scripts                    .= '<script type="text/javascript">enable_advanced_wysiwyg("wysiwyg");</script>';
        return $scripts;
    }
}
?>
